﻿//------------------------------------------------------------------------------
// Written for CP2011 Project @ JCU, 2011
// By Drewan O'Brien
//
// Executes a register request by first checking if that username has already
// been registerd.  If the username is already registered the client is notified
// that the username already exists.  If the username does not exist the the user
// is added to the database and a success notification is sent to the client. 
//------------------------------------------------------------------------------

using System;
using System.Linq;
using System.Collections.Generic;
using BluSteamServer.Model.DataAccessLayer;

namespace BluSteamServer.Model.TransactionImplementation
{
    public class RegisterTransaction : Transaction
    {
        #region Fields

        private readonly string _username;
        private readonly string _email;
        private readonly string _description;
        private readonly string _password;

        private bool _validated;

        #endregion

        #region Constructors

        public RegisterTransaction(string username, string email, string password)
        {
            _username = username;
            _email = email;
            _password = password;

            _validated = false;
        }

        #endregion

        #region Properties

        public bool Validated
        {
            get { return _validated; }
        }

        #endregion

        #region Methods

        public void Validate()
        {
            // search for user requesting to login
            Dictionary<string, object> user =
                new DataAccessObject().GetRecordByAttribute("Users", "username", _username);

            // username has already been registered
            if (user.Count != 0)
            {
                string message = string.Format("$CP2011~{0}~RESPONSE~USERNAME_EXISTS", _username);
                Network.Send(_username, message);
                return;
            }

            _validated = true;
        }

        public void Execute()
        {
            if (_validated)
            {
                Dictionary<string, object> user = new Dictionary<string, object>();
                user.Add("username", _username);
                user.Add("password", _password);
                user.Add("email", _email);
                new DataAccessObject().InsertIntoTable("Users", user);

                // notify client of registration success
                string message = string.Format("$CP2011~{0}~RESPONSE~REGISTER_SUCCESS", _username);
                Network.Send(_username, message);
            }
        }

        #endregion
    }
}
